package com.lesson5.prototype;

import java.io.*;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/8/28 18:09
 */
public class DeepPrototype implements Serializable, Cloneable
{
    public String name;
    public DeepCloneableTarget target;

    public DeepPrototype()
    {
    }

    //深拷贝的实现 clone方式
    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        Object obj = null;
        //基本数据类型的克隆可以直接完成
        obj = super.clone();
        //对引用类型需要单独处理
        DeepPrototype deepPrototype = (DeepPrototype) obj;
        deepPrototype.target = ((DeepCloneableTarget) target.clone());
        return deepPrototype;
    }

    //通过序列化方式实现
    public Object deepClone()
    {
        ByteArrayOutputStream bos = null;
        ByteArrayInputStream bis = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;

        try
        {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);//当前对象以对象流的方式输出

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepPrototype deepPrototype = (DeepPrototype) ois.readObject();
            return deepPrototype;
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        } finally
        {
            try
            {
                bis.close();
                bos.close();
                ois.close();
                oos.close();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
